package oa.hleast.xswl.controller.ws;

import lombok.extern.slf4j.Slf4j;
import oa.hleast.xswl.common.config.WebSocketConfig;
import oa.hleast.xswl.common.constant.ChatDateEnum;
import oa.hleast.xswl.service.chat.impl.WebSocketServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/api.ws/v1/server/{userId}")
@Service
@Slf4j
public class WebSocketServerController {

    private static WebSocketServerService webSocketServerService;


    @Autowired
    public void set(WebSocketServerService webSocketServerService){
        WebSocketServerController.webSocketServerService = webSocketServerService;
    }

    /**
     * 打开连接
     * @param userId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        try {
            webSocketServerService.onOpen(userId,session);
        }
        catch (Exception e){
            e.printStackTrace();
            log.error("websocket连接异常",e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("服务端发生了错误"+error.getMessage());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        try {
            WebSocketConfig.server.remove(userId);
        }
        catch (Exception e){
            log.error("websocket连接关闭异常",e);
        }
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(@PathParam("userId") String userId,String message, Session session) {
        try {
            webSocketServerService.handleMessage(userId,message,session, ChatDateEnum.TXT.name(),null);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }



}
